//
//  LCWOAuthWebViewControllers.swift
//  MyWB
//
//  Created by 李成万 on 16/6/25.
//  Copyright © 2016年 李成万. All rights reserved.
//

import UIKit
import SVProgressHUD
class LCWOAuthWebViewControllers: UIViewController {

    override func loadView() {
        
        webView.delegate = self
        loadWebView()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
     
        setNav()
        
        
    }
    
    
    let webView = UIWebView(frame:UIScreen.mainScreen().bounds)
    
    
    func loadWebView(){
        UIScreen.mainScreen().bounds
        
        
        
        webView.loadRequest(NSURLRequest(URL: NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(HUIDIAOYE)")!))
        
        view = webView
        
        
    }
    
    func setNav(){
        title = "OAuth 授权登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
    func cancel(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func autoFill(){
        let jsStr = "document.getElementById('userId').value='1136610153@qq.com',document.getElementById('passwd').value='ksda54290173/l'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
}

extension LCWOAuthWebViewControllers : UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print(error)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        
        guard let u = urlString where u.hasPrefix(HUIDIAOYE) else{
            return true
        }
        
        let query = request.URL?.query
        guard let q = query else{
            return true
        }
        let code = q.substringFromIndex("12345".endIndex)
        loadUserAccount(code)
        
        return false
    }
}

extension LCWOAuthWebViewControllers{
    func loadUserAccount(code:String){
        
        LCWNetworkingTools.sharedTools.oAuthLoadRequest(code, success: { (response) -> () in
            guard let res = response as? [String:AnyObject] else{
                return
            }
            let account = LCWUserAccount(dict: res)
            
            self.loadUserInfo(account)
            
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("请求出错")
        }
    }
    
    func loadUserInfo(account:LCWUserAccount){
        LCWNetworkingTools.sharedTools.oAuthLoadUserInfo(account, success: { (response) -> () in
            if let res = response{
                account.avatar_large = res["avatar_large"] as? String
                account.screen_name = res["screen_name"] as? String
                
                LCWUserAccountTools.sharedTool.setUserAccountInfo(account)
               
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVc, object: nil) 
                })
               

            }
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("请求出错")
        }
    }
}